package com.itheima.tlias08_14.aspect;

import com.alibaba.fastjson.JSONObject;
import com.itheima.tlias08_14.dto.LoginDTO;
import com.itheima.tlias08_14.entity.Log;
import com.itheima.tlias08_14.mapper.EmpMapper;
import com.itheima.tlias08_14.mapper.LogMapper;
import com.itheima.tlias08_14.utils.JwtUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

/**
 * @Aspect 标识切面类
 * @Component 标识为组件
 */
@Slf4j
@Aspect
@Component
public class LogAspect {

    @Resource
    HttpServletRequest request;
    @Resource
    EmpMapper empMapper;
    @Resource
    LogMapper logMapper;

    @Around("@annotation(com.itheima.tlias08_14.annotation.Log)")
    public Object insertLog(ProceedingJoinPoint point) {
        Log logInsert = new Log();
        //获取请求体中的Token
        String token = request.getHeader("token");
        //解析token中的信息
        JSONObject decode = JwtUtil.decode(token);
        String username = decode.getString("username");
        LoginDTO user = empMapper.selectByUsername(username);
        //获取操作员id
        logInsert.setOperateEmpId(user.getId());
        //获取操作员姓名
        String operateEmpName = user.getName();
        logInsert.setOperateEmpName(operateEmpName);
        //获取方法名
        String methodName = point.getSignature().getName();
        logInsert.setMethodName(methodName);
        //获取类名
        String className = point.getTarget().getClass().getName();
        logInsert.setClassName(className);
        //获取方法参数
        Object[] args = point.getArgs();
        String methodParams = Arrays.toString(args);
        logInsert.setMethodParams(methodParams);

        long start = System.currentTimeMillis();
        try {
            Object proceed = point.proceed();
            //获取返回值
            logInsert.setReturnValue(proceed.toString());
            long costTime = System.currentTimeMillis() - start;
            logInsert.setCostTime(costTime);
            logInsert.setOperateTime(LocalDateTime.now());
            logMapper.insertLog(logInsert);
            log.info("日志记录成功 {},Log执行时间为{}", className, costTime);
            return proceed;
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }

    }

}
